<template>
  <div class="file-table-wrapper">
    <!-- 文件表格 -->
    <el-table
        class="file-table"
        :class="'file-type-' + fileType().current()"
        ref="multipleTable"
        fit
        v-loading="loading"
        element-loading-text="文件加载中……"
        tooltip-effect="dark"
        :data="fileList"
        :default-sort="{ prop: 'dir', order: 'descending' }"
        @select-all="selectAllFileRow"
        @select="selectFileRow"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="dir" width="60" align="center">
        <template v-slot="scope">
          <img :src="setFileImg(scope.row)" style="height: 30px"/>
        </template>
      </el-table-column>
      <el-table-column prop="filename" :sort-by="['dir', 'filename']" sortable show-overflow-tooltip>
        <template v-slot:header>
          <span>文件名</span>
        </template>
        <template v-slot="scope">
          <div style="cursor:pointer;" @click="clickFileName(scope.row)">
            {{ filenameComplete(scope.row) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="fileType().isRecycle() ? '原路径' : '路径'" prop="pid" show-overflow-tooltip
                       v-if="fileType().isNotAll()">
        <template v-slot="scope">
          <span
              style="cursor: pointer;"
              title="点击跳转"
              @click="$router.push({ query: { pid: scope.row.pid, fileType: FILE_TYPE.ALL } })"
              v-text="getFilePath(scope.row.pid)"></span>
        </template>
      </el-table-column>
      <el-table-column
          label="类型"
          width="80"
          prop="extension"
          :sort-by="['dir', 'extension']"
          sortable
          show-overflow-tooltip
          v-if="selectedColumnList.includes('extension')"
      >
        <template v-slot="scope">
          <span v-if="scope.row.extension">{{ scope.row.extension }}</span>
          <span v-else>文件夹</span>
        </template>
      </el-table-column>
      <el-table-column
          label="大小"
          width="80"
          prop="fileSize"
          :sort-by="['dir', 'fileSize']"
          sortable
          show-overflow-tooltip
          align="right"
          v-if="selectedColumnList.includes('fileSize')"
      >
        <template v-slot="scope">
          <div style="padding: 0 10px;">{{ calculateFileSize(scope.row.fileSize) }}</div>
        </template>
      </el-table-column>
      <el-table-column
          label="修改日期"
          prop="updateTime"
          width="180"
          :sort-by="['dir', 'updateTime']"
          show-overflow-tooltip
          sortable
          v-if="selectedColumnList.includes('updateTime')"
      ></el-table-column>
      <el-table-column
          label="删除日期"
          prop="deleteTime"
          width="180"
          :sort-by="['dir', 'deleteTime']"
          show-overflow-tooltip
          sortable
          v-if="fileType().isRecycle() && selectedColumnList.includes('deleteTime')"
      ></el-table-column>
      <el-table-column :width="operaColumnWidth">
        <template v-slot:header>
          <span>操作</span>
          <!--
          <i
              class="el-icon-circle-plus"
              title="展开操作列按钮"
              @click="$store.commit('changeOperaColumnExpand', FOLD_TYPE.UNFOLD)"
          ></i>
          <i class="el-icon-remove" title="收起操作列按钮"
             @click="$store.commit('changeOperaColumnExpand', FOLD_TYPE.FOLD)"></i>
          -->
        </template>
        <template v-slot="scope">
          <div v-if="operaColumnExpand">        
            <el-button type="danger" size="mini" @click.native="deleteFileBtn(scope.row)">删除</el-button>
            <el-button type="success" size="mini" @click.native="recoverFileBtn(scope.row)"
                       v-if="fileType().isRecycle()">恢复
            </el-button>
            <el-button type="primary" size="mini" @click.native="showMoveFileDialog(scope.row)"
                       v-if="fileType().isNotRecycle()">移动
            </el-button>
            <el-button type="primary" size="mini" @click.native="clkRenameFile(scope.row)"
                       v-if="fileType().isNotRecycle()">重命名
            </el-button>
            <el-button type="success" size="mini" v-if="scope.row.dir==false && fileType().isNotRecycle()" @click="tapDownLoad(getDownloadPath(scope.row.id),scope.row)">
              下载
              <!-- <a
                  target="_blank"
                  style="display: block;color: inherit;"
                  :href="getDownloadPath(scope.row.id)"
                  :download="scope.row.filename + '.' + scope.row.extension"
              >下载</a  > -->
            </el-button>
            <!--            <el-button-->
            <!--                type="warning"-->
            <!--                size="mini"-->
            <!--                @click.native="unzipFile(scope.row)"-->
            <!--                v-if="fileType().isNotRecycle() && (scope.row.extension == 'zip' || scope.row.extension == 'rar')"-->
            <!--            >解压缩-->
            <!--            </el-button>-->
          </div>
          <el-dropdown trigger="click" v-else>
            <el-button size="mini">
              操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu v-slot:dropdown>
              <el-dropdown-item @click.native="deleteFileBtn(scope.row)">删除</el-dropdown-item>
              <el-dropdown-item @click.native="recoverFileBtn(scope.row)" v-show="fileType().isRecycle()">恢复
              </el-dropdown-item>
              <el-dropdown-item @click.native="showMoveFileDialog(scope.row)" v-show="fileType().isNotRecycle()">移动
              </el-dropdown-item>
              <el-dropdown-item @click.native="clkRenameFile(scope.row)" v-show="fileType().isNotRecycle()">重命名
              </el-dropdown-item>
              <!--              <el-dropdown-item-->
              <!--                  v-if="scope.row.extension === 'zip' && fileType().isNotRecycle()"-->
              <!--                  @click.native="unzipFile(scope.row)">解压缩-->
              <!--              </el-dropdown-item>-->
              <el-dropdown-item v-show="scope.row.dir == false && fileType().isNotRecycle()" @click="tapDownLoad(getDownloadPath(scope.row.id),scope.row)">
                下载
                <!-- <a
                    target="_blank"
                    style="display: block;color: inherit;"
                    :href="getDownloadPath(scope.row.id)"
                    :download="scope.row.filename + '.' + scope.row.extension">下载</a> -->
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {unzipfile, deleteFile, renameFile, deleteRecoveryFile, recoverRecycleFile} from '/@/request/file.js'
//import {mapGetters} from 'vuex'
import { computed, toRefs, reactive } from 'vue';
import {filenameComplete, filenameSplit} from "/@/utils/wangpanFiters.js";
import { wangpanGlobal }  from '/@/utils/wangpanGlobalConst';
import { ElMessage, ElMessageBox } from 'element-plus';
import {fileType,getThumbnailPath,getDownloadPath,getFileOnlineViewPathByOffice} from '/@/utils/wangpanGlobalFunction';
import { useStore } from '/@/store/index';
import { useRouter } from 'vue-router';
import { Session } from '/@/utils/storage';

import DownloadUnit from '/@/utils/shf/DownloadUnit';

export default {
  name: 'FileTable',
  emits: ['setSelectionFile', 'setOperationFile', 'setMoveFileDialogData', 'getTableDataByType'],
  props: {
    fileList: Array,  //  文件列表
    loading: Boolean
  },
  setup (props , { emit }){
  
  	const store=useStore();
  	const router=useRouter();
  	
  	const state = reactive({
      //  移动文件模态框数据
      dialogMoveFile: {
        isBatchMove: false,
        visible: false, //  是否可见
        fileTree: [], //  目录树
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      },
      viewFilePath: '',
      fileType: fileType,
      filenameComplete:filenameComplete,
      getDownloadPath:getDownloadPath,
      FOLD_TYPE:wangpanGlobal.gFOLD_TYPE,
    });

    const operaColumnWidth = computed(()=>{
      return fileType().isRecycle()
          ? 150 : operaColumnExpand
              ? isIncludeNormalFile ? 290 : 220 : 100
    });

    const selectedColumnList = computed(()=>{
    	return store.state.wangpanFileList.selectedColumnList === null
            ? ["extension", "fileSize", "updateTime", "deleteTime"]
            : store.state.wangpanFileList.selectedColumnList.split(",");
    }); 
    const operaColumnExpand = computed(()=>{
    	 return  store.state.wangpanFileList.operaColumnExpand !== null
                ? Number(store.state.wangpanFileList.operaColumnExpand)
                : document.body.clientWidth > 1280 ? wangpanGlobal.gFOLD_TYPE.UNFOLD : wangpanGlobal.gFOLD_TYPE.FOLD;
    
    }); 
    const getFilePath = (pid)=>{
    	let path = '/'
        let id = pid
        while (id) {
        	if (store.state.wangpanFileList.pathTreeMap[id])
        	{
	            path = '/' + store.state.wangpanFileList.pathTreeMap[id].name + path
	            id = store.state.wangpanFileList.pathTreeMap[id].pid
            }
            else 
            {
            	console.log(store.state.wangpanFileList.pathTreeMap);
            	console.log(id);
            	break;
            }
        }
        return path
    }; 
	const isIncludeNormalFile = computed((data)=>{
      return props.fileList.map((data) => data.dir).includes(false)
    });
    //  判断当前路径下是否有压缩文件
    const isIncludeZipRarFile= computed((data)=>{
      return (
          props.fileList.map((data) => data.extension).includes('zip') ||
          props.fileList.map((data) => data.extension).includes('rar')
      )
    });
    //  根据文件扩展名设置文件图片
    const setFileImg = (row)=> {
      if (!row.extension) {
        //  文件夹
        return wangpanGlobal.gFILE_IMG_MAP.get('dir')
      } else if (!wangpanGlobal.gFILE_IMG_TYPE_LIST.includes(row.extension)) {
        //  无法识别文件类型的文件
        return wangpanGlobal.gFILE_IMG_MAP.get('unknown')
      } else if (['jpg', 'png', 'jpeg', 'gif'].includes(row.extension)) {
        // 图片类型，直接显示缩略图
        return getThumbnailPath(row.id)
      } else {
        //  可以识别文件类型的文件
        return wangpanGlobal.gFILE_IMG_MAP.get(row.extension)
      }
    };
    //  计算文件大小
    const calculateFileSize = (size)=> {
      const B = 1024
      const KB = Math.pow(1024, 2)
      const MB = Math.pow(1024, 3)
      const GB = Math.pow(1024, 4)
      if (!size) {
        return '_'
      } else if (size < KB) {
        return (size / B).toFixed(0) + 'KB'
      } else if (size < MB) {
        return (size / KB).toFixed(1) + 'MB'
      } else if (size < GB) {
        return (size / MB).toFixed(2) + 'GB'
      } else {
        return (size / GB).toFixed(3) + 'TB'
      }
    };

    const tapDownLoad = (url,row)=>{
      // console.log(''+url);
      console.log('row = ',row);
      let {filename,extension} = row;
      
      // debugger;
      DownloadUnit.down(url,filename+"."+extension);
      //http://192.168.3.16:8089/transfer/download/6a58fac7aaf54913b34dd669982f6a38
    }

    //  点击文件名
    const clickFileName = (row)=> {
      //  若是目录则进入目录
      if (row.dir) {
      	console.log('click dir.........,so ......');
      	let val = {
            pid: row.id,
            fileType: fileType().current()
          };
        Session.set('WANGPAN_Qurey',val);
        router.push({
          query:val, 
        })
      }
      //  若是文件，则进行相应的预览
      else {
        //  若当前点击项是图片
        if (wangpanGlobal.gIMG_TYPE_LIST.includes(row.extension)) {
          let data = {
            imgReviewVisible: true,
            imgReviewList: [
              {
                id: row.id,
                fileUrl: getDownloadPath(row.id),
                downloadLink: getDownloadPath(row.id),
                filename: row.filename,
                extension: row.extension
              }
            ],
            activeIndex: 0
          }
          store.commit('wangpanImgReview/setImgReviewData', data)
        }
        //  若当前点击项是可以使用office在线预览的
        if (['ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx'].includes(row.extension)) {
          // window.open(this.getFileOnlineViewPathByOffice(row.id), '_blank')
          window.open(getDownloadPath(row.id), '_blank')
        }
        //  若当前点击项是pdf
        if (row.extension === 'pdf') {
          window.open(getDownloadPath(row.id), '_blank')
        }
        //  若当前点击项是html、js、css、json
        const CODE = ['html', 'js', 'css', 'json']
        if (CODE.includes(row.extension)) {
          window.open(getDownloadPath(row.id), '_blank')
        }
        //  若当前点击项是视频mp4格式
        if (wangpanGlobal.gVIDEO_TYPE_LIST.includes(row.extension)) {
          let data = {
            visible: true,
            url: this.getDownloadPath(row.id),
            filename: row.filename + '.' + row.extension
          }
          store.commit('wangpanVideoReview/setVideoReviewData', data)
        }
        //  若当前点击项是视频mp3格式
        if (wangpanGlobal.gMUSIC_TYPE_LIST.includes(row.extension)) {
          let data = {
            visible: true,
            url: this.getDownloadPath(row.id),
            filename: row.filename + '.' + row.extension
          }
          store.commit('wangpanVideoReview/setVideoReviewData', data)
        }
      }
    };

    /**
     * 表格勾选框事件
     */
    //  表格-全选事件, selectoin 勾选的行数据
    const selectAllFileRow = (selection)=> {
      emit('setSelectionFile', selection)
    };
    //  表格-选中一行事件, selectoin 勾选的行数据
    const selectFileRow = (selection)=> {
      emit('setSelectionFile', selection)
    };

    /**
     * 移动按钮相关事件
     */
    //  操作列-移动按钮：打开移动文件模态框
    const showMoveFileDialog = (file)=> {
      //  第一个参数: 是否批量移动；第二个参数：打开/关闭移动文件模态框
      emit('setOperationFile', file)
      emit('setMoveFileDialogData', false, true)
    };

    //  操作列-解压缩按钮
    const unzipFile = (fileInfo)=> {
      const loading = this.$loading({
        lock: true,
        text: '正在解压缩，请稍等片刻...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      unzipfile(fileInfo).then(() => {
        emit('getTableDataByType')
        store.dispatch('wangpanSideMenu/showStorage')
        ElMessage.success('解压成功')
        loading.close()
      }).catch(err => {
        console.log(err)
        ElMessage.error("系统忙，解压失败")
      })
    };

    /**
     * 恢复按钮事件
     */
    const recoverFileBtn = (fileInfo)=> {
      let data = {
        userFileId: fileInfo.id
      }
      if (fileType().isRecycle()) { //  回收站里 - 彻底删除
        ElMessageBox.confirm('是否恢复该文件?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          recoverRecycleFile(data).then(() => {
            ElMessage({
              type: 'success',
              message: filenameComplete(fileInfo) + '已恢复'
            })
            emit('getTableDataByType')
            store.dispatch('wangpanSideMenu/showStorage')
            store.dispatch('wangpanFileList/fetchPathTreeMap')
          }
        )
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消恢复'
          })
        })
      }
    };

    //  操作列-删除按钮
    const deleteFileBtn = (fileInfo)=> {
      if (fileType().isRecycle()) { //  回收站里 - 彻底删除
        ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          confirmDeleteFile(fileInfo, true)
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {  //  非回收站
        ElMessageBox.confirm('删除后可在回收站查看, 是否继续删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          confirmDeleteFile(fileInfo, false)
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    };
    //  删除文件模态框-确定按钮
    const confirmDeleteFile = (fileInfo, type)=> {
      let data = {userFileId: fileInfo.id}
      if (type) {  //  回收站中删除
        deleteRecoveryFile(data).then(() => {
          emit('getTableDataByType')
          store.dispatch('wangpanSideMenu/showStorage')
          ElMessage.success('删除成功')
          store.dispatch('wangpanFileList/fetchPathTreeMap')
        }).catch(err => {
          console.log(err)
          ElMessage.error("系统忙，删除失败")
        })
      } else {  //  非回收站删除
        deleteFile(data).then(() => {
          emit('getTableDataByType')
          store.dispatch('wangpanSideMenu/showStorage')
          //ElMessage.success('删除成功')
        }).catch(err => {
          console.log(err)
          //ElMessage.error("系统忙，删除失败")
        })
      }
    };
    // 文件重命名
    const clkRenameFile = (fileInfo)=> {
      let filename = filenameComplete(fileInfo)
      ElMessageBox.prompt('请输入文件名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: filename
      }).then(({value}) => {
        let name = filenameSplit(value)
        if (!name.filename) {
          ElMessage.error("仅支持文件改名")
        }
        if (fileInfo.filename === name.filename && fileInfo.extension === name.extension) {
          ElMessage.error("文件名未发生改变")
        }
        fileInfo.oldFilename = fileInfo.filename
        fileInfo.oldExtension = fileInfo.extension
        fileInfo.filename = name.filename
        fileInfo.extension = name.extension
        confirmRenameFile(fileInfo)
      }).catch(() => {      	
        ElMessage({
          type: 'info',
          message: '取消输入'
        })
      })
    };
    // 文件重命名模态框 确定按钮
    const confirmRenameFile = (fileInfo)=> {
      console.log(fileInfo)
      let data = {
        userFileId: fileInfo.id,
        filename: fileInfo.filename
      }
      if (!fileInfo.dir) {
        data.extension = fileInfo.extension
      }
      renameFile(data).then(() => {
        emit('getTableDataByType')
        store.dispatch('wangpanSideMenu/showStorage')
        ElMessage.success('重命名成功')
      }).catch((err) => {
        fileInfo.filename = fileInfo.oldFilename
        fileInfo.extension = fileInfo.oldExtension
        console.error(err)
        ElMessage.error("系统忙，重命名失败")
      })    
  };

  return {
			selectAllFileRow,
			selectFileRow,
			selectedColumnList,
			operaColumnWidth,
			getFilePath,
			setFileImg,
			clickFileName,
      tapDownLoad,
			calculateFileSize,
			operaColumnExpand,
			deleteFileBtn,
			clkRenameFile,
			showMoveFileDialog,
			recoverFileBtn,
			...toRefs(state),
		};
	},
}
</script>

<style lang="stylus" scoped>
@import '../../styles/varibles.styl'
@import '../../styles/mixins.styl'
.file-table-wrapper
  margin-top 2px

  .file-type-0
    height calc(100vh - 206px) !important

    :deep(.el-table__body-wrapper)
      height calc(100vh - 264px) !important

  .file-type-6
    height calc(100vh - 211px) !important

    :deep(.el-table__body-wrapper)
      height calc(100vh - 263px) !important

  .file-table
    width 100% !important
    height calc(100vh - 203px)

    :deep(.el-table__header-wrapper)
      th
        background $tabBackColor
        padding 8px 0

      .el-icon-circle-plus, .el-icon-remove
        margin-left 6px
        cursor pointer
        font-size 16px

        &:hover
          color $Primary

    :deep(.el-table__body-wrapper)
      height calc(100vh - 255px)
      overflow-y auto
      setScrollbar(10px)

      td
        padding 8px 0

  .img-review-wrapper
    position fixed
    top 0
    right 0
    bottom 0
    left 0
    overflow auto
    width 100%
    height 100%
    z-index 2010
    text-align center
    display flex
    align-items center
    animation imgReviewAnimation 0.3s
    -webkit-animation imgReviewAnimation 0.3s /* Safari and Chrome */
    animation-iteration-count 0.3
    -webkit-animation-iteration-count 0.3
    animation-fill-mode forwards
    -webkit-animation-fill-mode forwards /* Safari 和 Chrome */
    @keyframes imgReviewAnimation
      0%
        background transparent
      100%
        background rgba(0, 0, 0, 0.8)
    @keyframes imgReviewAnimation
      0%
        background transparent
      100%
        background rgba(0, 0, 0, 0.8)

    .img-large
      margin 0 auto
      max-width 80%
      max-height 100%
</style>
